const zmfDbClient = uniCloud.importObject("zmf-db-client");
const types = {
	clear: "clear",
	getList: "getList",
	addWords: "addWords",
}
export default {
	namespaced: true,
	state: {
		list: [],
		hasNext: true
	},
	getters: {

	},
	mutations: {
		[types.clear](state) {
			state.list = []
			state.hasNext = true
		},
		async [types.getList](state, {
			uid,
			type,
			start,
			page
		}) {
			if (state.hasNext === false) {
				return
			}
			const param = {
				uid: uid,
				type: type,
				start_num: start,
				page_num: page
			}
			const resp = await zmfDbClient.getZmfAccountInfoByPage(param);
			const {
				errCode,
				userRecord
			} = resp
			if (userRecord !== undefined && userRecord.length > 0) {
				const temp = state.list
				state.list = temp.concat(userRecord);
			}

			if (userRecord !== undefined && userRecord.length < page) {
				state.hasNext = false
			}

		}
	},
	actions: {
		async clear({
			commit
		}) {
			commit(types.clear)
		},
		async getList({
			commit
		}, {
			uid,
			type,
			start,
			page
		}) {
			if (uid === undefined || type === undefined || start === undefined || page === undefined) {
				console.error("参数错误");
				return
			}
			commit(types.getList, {
				uid,
				type,
				start,
				page
			})
		},
		async addWords({
			commit,dispatch
		}, {
			uid,
			type,
			source,
			words,
			scores,
			consume,
			expire_time,
			that
		}) {
			const date = new Date().getTime();
			// 添加积分使用
			if(true){
				const scoresParam = {
					user_id:uid,
					score:consume,
					type:2,
					balance:scores - consume,
					comment:"积分兑换",
					create_date:date
				}
				const resp = await zmfDbClient.addUniIdScores(scoresParam)
				const {errCode, userRecord} = resp
				if (errCode !== 0) {
					uni.showToast({
						icon:"error",
						title:"兑换失败",
						duration:2000
					})
					return
				}
				try {
					let scores =  that.$store.state.loginStore.scores
					scores.unshift(scoresParam)
					uni.setStorageSync('cu-scores',JSON.stringify(scores));
					// await that.$store.dispatch('loginStore/initBaseInfo');
				} catch (e) {
					console.error('StorageSync异常-key:cu-scores')
				}
				
			}
			
			// 兑换字符
			if(true){
				const wordsParam = {
					uid,
					type,
					source,
					create_date:date,
					expire_date:date + expire_time,
					words,
					used:0,
					use_up_mark:false
				}
				
				const wordsResp = await zmfDbClient.addZmfAccountInfo(wordsParam)
				const {errCode, userRecord} = wordsResp
				if (errCode !== 0) {
					uni.showToast({
						icon:"error",
						title:"兑换失败",
						duration:2000
					})
					return
				}
				
				let accountinfo =  that.$store.state.loginStore.accountinfo
				accountinfo.unshift(wordsParam)
				uni.setStorageSync('cu-accountinfo',JSON.stringify(accountinfo));
				
				uni.showToast({
					icon:"success",
					title:"兑换成功",
					duration:2000
				})
			}
		},
	}
}